package fr.paulmasson.jfreex.db;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.exception.JDBCConnectionException;
import org.hsqldb.server.Server;


@SuppressWarnings("deprecation")
public class DbManager {

	
	private static SessionFactory sf = null;
	private static Session s = null;
	private static Server server;
	
	public static void startDbServer() {
		try {
			server = (Server) Class.forName("org.hsqldb.Server").newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		server.setDatabasePath(0,"jfreex"); 
        server.setDatabaseName(0,"jfreex");
        server.setLogWriter(null);
        server.setSilent(true);
        server.setTrace(false);
        server.setErrWriter(null);
		server.start();
		sf = new AnnotationConfiguration().configure().buildSessionFactory();
		s = sf.openSession();
	}
	
	public static void stopDbServer() {
		s.disconnect();
		server.stop();
	}
	
	private static void commit() {
		s.getTransaction().commit();
	}
	
	private static void beginTransaction() {
		try {
		s.beginTransaction();
		} catch  (JDBCConnectionException e) {
			
		}
	}
	
	public static void saveEntity(Object o) {
		beginTransaction();
		s.save(o);
		commit();
	}
	public static void updateEntity(Object o) {
		beginTransaction();
		s.update(o);
		commit();
	}
	
	@SuppressWarnings("unchecked")
	public static ArrayList<Object> get(String query) {
		beginTransaction();
		ArrayList<Object> res = (ArrayList<Object>) s.createQuery(query).list();
		commit();
		return res;
	}
}
